package com.xiao.common.aspect;

import com.alibaba.nacos.common.utils.StringUtils;
import com.xiao.common.common.ErrorCode;
import com.xiao.common.exception.BusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验切面（处理@AuthCheck注解）
 */
@Aspect
@Component
public class AuthCheckAspect {

    @Around("@annotation(authCheck)")
    public Object doAuthCheck(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取当前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取请求上下文失败");
        }
        HttpServletRequest request = requestAttributes.getRequest();

        // 从请求头获取网关传递的用户角色（X-User-Role由网关拦截器设置）
        String userRole = request.getHeader("X-User-Role");
        if (StringUtils.isBlank(userRole)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未获取到用户角色");
        }

        // 校验必须的角色
        String mustRole = authCheck.mustRole();
        if (StringUtils.isNotBlank(mustRole) && !mustRole.equals(userRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问");
        }

        // 权限通过，执行原方法
        return joinPoint.proceed();
    }
}